package org.atlantis.net.base;

import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;

public class InetAddressExample {

	public static void main(String[] args) throws Exception {

		/* 对于本机的地址的查找 */

		// 获取电脑上所有的网卡接口（至少有一个：就是127.0.0.1这个IP回环接口）
		Enumeration<NetworkInterface> interfaceList = NetworkInterface
				.getNetworkInterfaces();
		if (interfaceList == null) {
			System.err.println("Warm! --No interfaces found--");
		}
		while (interfaceList.hasMoreElements()) {
			NetworkInterface iface = interfaceList.nextElement();
			System.out.println("Interface " + iface.getName() + ":");
			// 每个网卡上绑定的IP列表（一般来说是一个，也可以绑定多个）
			Enumeration<InetAddress> addrList = iface.getInetAddresses();
			if (!addrList.hasMoreElements()) {
				System.err.println("\t(Warm! No addresses for this interface)");
			}
			while (addrList.hasMoreElements()) {
				InetAddress address = addrList.nextElement();
				System.out.print("\tAddress "
						+ ((address instanceof Inet4Address ? "(v4)"
								: (address instanceof Inet6Address ? "(v6)"
										: "(?)"))));
				System.out.println(": " + address.getHostAddress());
			}
		}

		/* 对于网络的地址的查找 */
		String[] hosts = { "baidu.com", "wusesky.com" };
		for (String host : hosts) {
			System.out.println(host + ": ");
			InetAddress[] addrList = InetAddress.getAllByName(host);
			for (InetAddress addr : addrList) {
				System.out.print("\t" + addr.getHostName() + "/"
						+ addr.getHostAddress());
			}
			System.out.println();
		}
	}
}
